package cn.lijian.goods.order.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.commons.CommonUtils;
import cn.itcast.jdbc.TxQueryRunner;
import cn.lijian.goods.book.domain.Book;
import cn.lijian.goods.order.domain.Order;
import cn.lijian.goods.order.domain.OrderItem;
import cn.lijian.goods.pager.Expression;
import cn.lijian.goods.pager.PageBean;
import cn.lijian.goods.pager.PageConstants;

public class OrderDao {
	
	private QueryRunner qr=new TxQueryRunner();
	/**
	 * 查询订单状态
	 * @param oid
	 * @return
	 * @author lijian
	 * @throws SQLException 
	 */
	public int findStatus(String oid) throws SQLException{
		String sql="select status from t_order where oid=?";  
		Number number=(Number) qr.query(sql, new ScalarHandler(),oid);
		return number.intValue();
	}
	/**
	 * 修改订单状态
	 * @param oid
	 * @param status
	 * @throws SQLException
	 * @author lijian
	 */
	public void updateStatus(String oid,int status) throws SQLException{
		String sql="update t_order set status=? where oid=?";
		qr.update(sql,status,oid);
	}
	
	public Order load(String oid) throws SQLException{
		String sql="select * from t_order where oid=?";
		Order order=qr.query(sql, new BeanHandler<Order>(Order.class),oid);
		loadOrderItem(order);//为当前订单加载它的所有订单条目
		return order;
	}
	
	/**
	 * 生成订单
	 * @param order
	 * @author lijian
	 * @throws SQLException 
	 */
	public void add(Order order) throws SQLException{
		String sql="insert into t_order values(?,?,?,?,?,?)";;
		Object[]params={order.getOid(),order.getOrdertime(),order.getTotal(),order.getStatus(),order.getAddress(),order.getOwner().getUid()};
		qr.update(sql,params);
		
		sql="insert into t_orderitem values(?,?,?,?,?,?,?,?)";
		int len=order.getOrderItemList().size();
		Object[][]objs=new Object[len][];
		for(int i=0;i<len;i++){
			OrderItem item=order.getOrderItemList().get(i);
			objs[i]=new Object[]{item.getOrderItemId(),item.getQuantity(),item.getSubtotal(),item.getBook().getBid(),item.getBook().getBname(),item.getBook().getCurrPrice(),item.getBook().getImage_b(),order.getOid()};;
			
		}
		qr.batch(sql, objs);//执行批处理
		
	}
	
	public PageBean<Order> findByStatus(int status,int pc) throws SQLException{
		List<Expression>exList=new ArrayList<Expression>();
		exList.add(new Expression("status","=",status+""));
		return findByCriteria(exList, pc);
		
	}
	
	
	/**
	 * 按用户查询订单
	 * @param uid
	 * @param pc
	 * @return
	 * @throws SQLException
	 * @author lijian
	 */
	public PageBean<Order> findByUser(String uid,int pc) throws SQLException{
		List<Expression>exList=new ArrayList<Expression>();
		exList.add(new Expression("uid","=",uid));
		return findByCriteria(exList, pc);
		
	}
	/**
	 * 查询所有
	 * @return
	 * @throws SQLException
	 * @author lijian
	 */
	public PageBean<Order> findAll(int pc) throws SQLException{
		List<Expression>exList=new ArrayList<Expression>();
		return findByCriteria(exList, pc);
		
	}
	
	private PageBean<Order> findByCriteria(List<Expression> expList,int pc) throws SQLException{
		int pageSize=PageConstants.BOOK_SIZE;
		//生成 where 子句
		StringBuffer whereSql=new StringBuffer(" where 1=1 ");
		//这个 list 存放 各个参数的值
		List<Object>params=new ArrayList<Object>();
		for(Expression ex:expList){
			whereSql.append(" and ").append(ex.getName()).append(" "+ex.getOperation()).append(" ");
			if(!ex.getOperation().trim().equals("is null")){
				whereSql.append("?");
				params.add(ex.getValue());
			}
		}
		
		/*	System.out.println("*******"+whereSql);
		System.out.println(params);*/
		
		String sql="select count(*) from t_order "+whereSql;
		Number num=(Number)qr.query(sql, new ScalarHandler(),params.toArray());
		int totalRecord=num.intValue();
		
		sql="select * from t_order "+whereSql+" order by ordertime desc limit ?,?";;
		params.add((pc-1)*pageSize);//第一个问号，从第几个开始查询，当前页首行记录的下标
		params.add(pageSize);//第二个问号，一共查询几行
		
		List<Order>beanList=qr.query(sql, new BeanListHandler<Order>(Order.class),params.toArray());
		for(Order order:beanList){
			loadOrderItem(order);
		}
		PageBean<Order>pb=new PageBean<Order>();
		pb.setBeanList(beanList);
		pb.setPageCurrent(pc);
		pb.setPageSize(pageSize);
		pb.setTotalRecord(totalRecord);
		
		return pb;
		
	}
	/**
	 * 为指定的order 加载它的所有 orderItem
	 * @param order
	 * @author lijian
	 * @throws SQLException 
	 */
	private void loadOrderItem(Order order) throws SQLException{
		String sql= "select * from t_orderitem where oid=?";
		List<Map<String,Object>>map=qr.query(sql, new MapListHandler(),order.getOid());
		List<OrderItem>orderItemList=toOrderItemList(map);
		order.setOrderItemList(orderItemList);
	}
	
	/**
	 * 把多个 Map 转换成 多个 OrderItem
	 * @param mapList
	 * @return
	 * @author lijian
	 */
	private List<OrderItem> toOrderItemList(List<Map<String,Object>>mapList){
		List<OrderItem>list=new ArrayList<OrderItem>();
		for(Map<String,Object>map:mapList){
			OrderItem orderItem=toOrderItem(map);
			list.add(orderItem);
		}
		return list;
		
	}
	/**
	 * 把 一个 Map 转换成 一个 orderitem
	 * @param map
	 * @return
	 * @author lijian
	 */
	private OrderItem toOrderItem(Map<String, Object> map) {
		OrderItem orderItem=CommonUtils.toBean(map, OrderItem.class);
		Book book=CommonUtils.toBean(map, Book.class);
		orderItem.setBook(book);
		return orderItem;
	}

}
